package com.himiotech.core.framework.config.mybatisplus.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.himiotech.core.framework.helper.utils.HimioUtils;
import com.himiotech.core.framework.helper.utils.ShiroUtils;
import org.apache.ibatis.reflection.MetaObject;

import java.time.LocalDateTime;

/**
 * 自动设置一些公共字段
 *
 * @author wuwenbin
 */
public class HimioMetaObjectHandler implements MetaObjectHandler {

    private static final String DEFAULT_CREATE_BY = "999999999";
    private static final String DEFAULT_CREATE_BY_NAME = "系统";

    /**
     * 插入元对象字段填充（用于插入时对公共字段的填充）
     *
     * @param metaObject 元对象
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "gmtCreate" , LocalDateTime::now, LocalDateTime.class);
        try {
            HimioUtils.checkShiroSecurityManager();
            this.strictInsertFill(metaObject, "createBy" , ShiroUtils::getUserIdStr, String.class);
            this.strictInsertFill(metaObject, "createByName" , ShiroUtils::getLoginName, String.class);
        } catch (Exception e) {
            this.strictInsertFill(metaObject, "createBy" , () -> DEFAULT_CREATE_BY, String.class);
            this.strictInsertFill(metaObject, "createByName" , () -> DEFAULT_CREATE_BY_NAME, String.class);
        }
    }

    /**
     * 更新元对象字段填充（用于更新时对公共字段的填充）
     *
     * @param metaObject 元对象
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, "gmtModified" , LocalDateTime::now, LocalDateTime.class);
        try {
            HimioUtils.checkShiroSecurityManager();
            this.strictUpdateFill(metaObject, "modifiedBy" , ShiroUtils::getUserIdStr, String.class);
            this.strictUpdateFill(metaObject, "modifiedByName" , ShiroUtils::getLoginName, String.class);
        } catch (Exception e) {
            this.strictUpdateFill(metaObject, "modifiedBy" , () -> DEFAULT_CREATE_BY, String.class);
            this.strictUpdateFill(metaObject, "modifiedByName" , () -> DEFAULT_CREATE_BY_NAME, String.class);
        }
    }
}
